﻿# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QPushButton


class ImageButton(QPushButton):
    def __init__(self, parent=None):
        super(ImageButton, self).__init__(parent)
        self.status = 0
        self.has4Status = False

    def loadPixmap(self, pic_name, has4Status=False):
        self.pixmap = QPixmap(pic_name)
        self.has4Status= has4Status
        if has4Status:
            self.btn_width = self.pixmap.width() / 4
        else:
            self.btn_width = self.pixmap.width()
        self.btn_height = self.pixmap.height()
        self.setFixedSize(self.btn_width, self.btn_height)

    def enterEvent(self, event):
        if not self.isChecked() and self.isEnabled():
            self.status = 1
            self.update()

    def setDisabled(self, bool):
        super(ImageButton, self).setDisabled(bool)
        if not self.isEnabled():
            self.status = 2
            self.update()
        else:
            self.status = 0
            self.update()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.status = 2
            self.update()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.clicked.emit(True)
        if not self.isChecked():
            self.status = 3
        if self.menu():
            self.menu().exec_(event.globalPos())
        self.update()

    def leaveEvent(self, event):
        if not self.isChecked() and self.isEnabled():
            self.status = 0
            self.update()

    def paintEvent(self, event):
        self.painter = QPainter()
        self.painter.begin(self)
        if self.has4Status:
            self.painter.drawPixmap(self.rect(),
                                    self.pixmap.copy(self.btn_width * self.status, 0, self.btn_width, self.btn_height))
        else:
            self.painter.drawPixmap(self.rect(), self.pixmap.copy(0, 0, self.btn_width, self.btn_height))
        self.painter.end()

